package com.cy.service;


import com.cy.bfzcommons.mapper.CartMapper;
import com.cy.bfzcommons.pojo.Cart;
import com.cy.bfzcommons.pojo.Product;
import com.cy.bfzcommons.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartMapper cartMapper;

    //添加倒购物车
    @Override
    public String saveCart(Integer userId,Integer productId) {
        if(userId == null || userId == 0) return "获取用户失败";
        if(productId == null || productId == 0) return "获取商品信息失败";
        Cart cart = new Cart().setProductId(productId).setUserId(userId);
        int insert = cartMapper.insert(cart);
        if(insert == 1){
            return null;
        }
        return "添加购物车失败";
    }

    //查询所有购物车物品
    @Override
    public List<Product> findCart(Integer id) {
        if(id == null || id == 0) return null;
        List<Product> products = cartMapper.findproduct(id);
        return products;
    }

    //删除购物车物品
    @Transactional
    @Override
    public String deleteCart(Integer productId, Integer userId) {
        if(userId == null || userId == 0) return "获取用户失败";
        if(productId == null || productId == 0) return "获取商品信息失败";
        Map<String ,Object> columnmap = new HashMap<>();
        columnmap.put("product_id", productId);
        columnmap.put("user_id", userId);
        int i = cartMapper.deleteByMap(columnmap);
        if(i == 1){
            return null;
        }else if(i > 1){
            throw new RuntimeException("数据库错误");
        }
        return "删除失败";
    }



}
